package com.atguigu.day07;

import com.atguigu.util.Event;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

public class Example6 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        var leftStream = env
                .fromElements(
                        new Event("key-1", "left", 10 * 1000L),
                        new Event("key-1", "left", 12 * 1000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner((e, t) -> e.ts)
                );

        var rightStream = env
                .fromElements(
                        new Event("key-1", "right", 6 * 1000L),
                        new Event("key-1", "right", 11 * 1000L),
                        new Event("key-1", "right", 17 * 1000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner((e, t) -> e.ts)
                );

        leftStream
                .join(rightStream)
                .where(left -> left.key)
                .equalTo(right -> right.key)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .apply((first, second) -> first + " --> " + second)
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
